package com.fu.mr.bluetoothdchat;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.content.Intent;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;

/**
 * <pre>
 *     author : Mr.Fu
 *     e-mail : 18622268981@163.com
 *     time   : 2020/03/06
 *     desc   : 蓝牙控制管理类
 *     version: 1.0
 * </pre>
 */

public class BluetoothManager {

    private static BluetoothManager mInstance = null;

    private BluetoothAdapter mAdapter;

    public BluetoothManager() {

        mAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public static BluetoothManager getInstance() {

        if (mInstance == null) {
            synchronized (BluetoothManager.class) {
                if (mInstance == null) {
                    mInstance = new BluetoothManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 是否支持蓝牙相关操作(判断设备的蓝牙功能是否存在或能否正常工作)
     *
     * @return
     */
    public boolean isSupported() {

        return mAdapter != null;
    }

    /**
     * 是否已经打开蓝牙
     *
     * @return
     */
    public boolean isEnabled() {

        return mAdapter.isEnabled();
    }

    /**
     * 打开蓝牙(无提示)
     */
    public void open() {

        if (!isEnabled()) {
            mAdapter.enable();
        }
    }

    /**
     * 打开蓝牙(有提示)
     *
     * @param activity
     * @param requestCode
     */
    public void open(Activity activity, int requestCode) {

        if (!isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 获取已配对列表
     *
     * @return
     */
    public Set<BluetoothDevice> getBondedDevices() {

        return mAdapter.getBondedDevices();
    }

    /**
     * 是否正在进行搜索设备操作
     *
     * @return
     */
    public boolean isDiscovering() {

        return mAdapter.isDiscovering();
    }

    /**
     * 开始搜索
     */
    public void startDiscovery() {

        if (!isDiscovering()) {
            mAdapter.startDiscovery();
        }
    }

    /**
     * 停止(取消)搜索
     */
    public void cancelDiscovery() {

        if (isDiscovering()) {
            mAdapter.cancelDiscovery();
        }
    }

    /**
     * 获取远程设备
     *
     * @param address
     * @return
     */
    public BluetoothDevice getRemoteDevice(String address) {

        return mAdapter.getRemoteDevice(address);
    }

    /**
     * 获取客户端设备
     *
     * @param name
     * @param uuid
     * @return
     */
    public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) {

        try {
            return mAdapter.listenUsingRfcommWithServiceRecord(name, uuid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
